package com.gzc.just.play.last.war.balanceserver.handler;



import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;

import com.gzc.just.play.last.war.balanceserver.manager.ServerManager;

import io.netty.channel.ChannelHandlerContext;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;



import java.util.Map;



/**

 * 璐熻浇鍧囪　澶勭悊鍣

 * 澶勭悊璐熻浇鍧囪　鐩稿叧鐨勬秷鎭锛屽傝幏鍙栨渶灏戣礋杞界殑鏈嶅姟鍣

 */

@Component("balance-loadBalanceHandler")
public class LoadBalanceHandler implements SimpleMessageHandler {

    private static final Logger logger = LoggerFactory.getLogger(LoadBalanceHandler.class);

    

    @Autowired

    private ServerManager serverManager;

    

    private static final int LOAD_BALANCE = 2002;

    

    @Override

    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {

        // 浠庢秷鎭涓瑙ｆ瀽鏈嶅姟鍣ㄧ被鍨嬶紙鍙閫夛級

        String serverType = extractServerType(message);

        

        // 鑾峰彇鏈灏戣礋杞界殑鏈嶅姟鍣

        Map<String, Object> serverInfo;

        if (serverType != null && !serverType.trim().isEmpty()) {

            // 鑾峰彇鎸囧畾绫诲瀷鐨勬渶灏戣礋杞芥湇鍔″櫒

            serverInfo = serverManager.getLeastLoadedServerByType(serverType);

            logger.info("Client requested least loaded server of type: {}", serverType);

        } else {

            // 鑾峰彇浠绘剰绫诲瀷鐨勬渶灏戣礋杞芥湇鍔″櫒

            serverInfo = serverManager.getLeastLoadedServer();

            logger.info("Client requested least loaded server of any type");

        }

        

        // 鍙戦佽礋杞藉潎琛″搷搴

        if (serverInfo != null) {

            sendLoadBalanceResponse(ctx, serverInfo, true, "Server selected successfully");

            logger.info("Selected server: {} ({})", 

                       serverInfo.get("serverId"), serverInfo.get("serverName"));

        } else {

            sendLoadBalanceResponse(ctx, null, false, "No suitable server available");

            logger.warn("No suitable server available for request");

        }

    }

    

    private String extractServerType(Object message) {

        // 瀹為檯瀹炵幇涓搴旇ヤ粠娑堟伅瀵硅薄涓瑙ｆ瀽鏈嶅姟鍣ㄧ被鍨

        // 杩欓噷杩斿洖绀轰緥鍊

        return "scene"; // 绀轰緥锛氶粯璁よ繑鍥炲満鏅鏈嶅姟鍣ㄧ被鍨

    }

    

    private void sendLoadBalanceResponse(ChannelHandlerContext ctx, Map<String, Object> serverInfo, 

                                        boolean success, String message) {

        // 瀹為檯瀹炵幇涓搴旇ユ瀯閫犲苟鍙戦佽礋杞藉潎琛″搷搴旀秷鎭

        logger.info("Sending load balance response: success={}, message={}", success, message);

        

        // 绀轰緥锛氭墦鍗版湇鍔″櫒淇℃伅鍐呭癸紙瀹為檯瀹炵幇涓搴旇ュ皢淇℃伅搴忓垪鍖栦负鍝嶅簲娑堟伅锛

        if (success && serverInfo != null) {

            logger.debug("Selected server info:");

            logger.debug("Server ID: {}", serverInfo.get("serverId"));

            logger.debug("Server Name: {}", serverInfo.get("serverName"));

            logger.debug("Server Type: {}", serverInfo.get("serverType"));

            logger.debug("Server Host: {}", serverInfo.get("host"));

            logger.debug("Server Port: {}", serverInfo.get("port"));

            logger.debug("Current Load: {}", serverInfo.get("load"));

            logger.debug("Max Load: {}", serverInfo.get("maxLoad"));

        }

    }



    @Override

    public int getMessageId() {

        return LOAD_BALANCE;

    }

    

    @Override

    public String getName() {

        return "LoadBalanceHandler";

    }

    

    @Override

    public Logger getLogger() {

        return logger;

    }

}